package com.example.demorabbitmq1.rabbit.order.cancel.queue;

import com.example.demorabbitmq1.config.RabbitForOrderCancelConfig;
import com.example.demorabbitmq1.model.MsgForOrderCancel;
import com.google.gson.Gson;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @Author: wangxc
 * @GitHub: https://github.com/vector4wang
 * @CSDN: http://blog.csdn.net/qqhjqs?viewmode=contents
 * @BLOG: http://vector4wang.tk
 * @wxid: BMHJQS
 */
@Component
public class DelayForOrderCancelSender {
	@Autowired
	private AmqpTemplate rabbitTemplate;

	/**
	 * 在消息上设置时间
	 * @param msg
	 */
	public void sendDelayMsg1(MsgForOrderCancel msg) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		System.out.println(msg.getId() + " 延迟消息发送时间:" + sdf.format(new Date()));

		Gson gson=new Gson();
		String string = gson.toJson(msg);//把对象转为JSON格式的字符串
		rabbitTemplate.convertAndSend(RabbitForOrderCancelConfig.DELAY_EXCHANGE_NAME_FOR_ORDERCANCEL, RabbitForOrderCancelConfig.ROUTING_KEY_FOR_ORDERCANCEL, string, new MessagePostProcessor() {
			@Override
			public Message postProcessMessage(Message message) throws AmqpException {
				message.getMessageProperties().setExpiration(msg.getTtl() + "");
				return message;
			}
		});
	}



}
